package projet2_ro;

import java.io.StreamTokenizer;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
 * This class parses the file in argument of the constructor and resolves the equation system given in it
 * @author Houdemer and Rigon
 */
public class Probleme {
    
    int n; //Nombre de variables
    StreamTokenizer tok;
    
    /**
     * Constructor, read the file and display the solution of the equation system
     * @param filename the file where the equations are
     * @throws IOException because sometimes it happens...sadly
     * @throws EquationException if the equation makes no sense
     */
    public Probleme(String filename) throws IOException, EquationException{
        try{
        tok = new StreamTokenizer(new FileReader(filename));
        }catch(FileNotFoundException e){
            System.out.println("ERREUR: Fichier non trouve.");
            System.exit(0);
        }
        tok.nextToken(); //On ignore le nombre d'equations
        int i,j,b;
        
        tok.nextToken();
        
        n = (int) tok.nval; //On recupere le nombre de variables

        //Ici on cree un ufind de taille n+1 vu que sinon la ieme variable serait a la case i-1, la case 0 ne sera donc pas utilisee
        UFind uf = new UFind(n);

        
        tok.nextToken();
        do{
             //On recupere le premier nombre de l'equation
            i = (int) tok.nval;
            
            tok.nextToken();
            j = (int) tok.nval; //On recupere le second nombre de l'equation
            
            tok.nextToken();
            
            if((b = (int) tok.nval) == 0){
                uf.union(i, j);
            }
            else if (b == 1){
                uf.unionOpposite(i, j);
            }
            // Apres avoir recupere le booleen resultat on test voir si il vaut bien 0 ou 1
            else{
                throw new EquationException("L'equation n'a pas comme resultat un booleen.");
            }               
            tok.nextToken();
        }while(tok.ttype != tok.TT_EOF);

        uf.getTableau();
        uf.makeEnum();
    }
}
